package main

import (
	"fmt"
	"sync"
	"time"
)

func main() {
	//队列长度为10
	ch := make(chan string, 10)
	//等待完成
	wg:=sync.WaitGroup{}
	wg.Add(1)
	lock := sync.Mutex{}

	for i := 1; i < 5; i++ {
		go producer(ch, i, lock)
	}
	for i := 1; i < 5; i++ {
		go consumer(ch, i, lock)
	}
	wg.Wait()
}

func producer(ch chan<- string, index int, lock sync.Mutex) {
	ticker := time.NewTicker(time.Millisecond * 200)
	defer ticker.Stop()
	i := 0
	for range ticker.C {
		message := "生产者：" + fmt.Sprint(index) + "发送消息：" + fmt.Sprint(i)
		//加锁
		lock.Lock()
		ch <- message
		lock.Unlock()
		fmt.Println(message)
		i++
	}

}

func consumer(ch <-chan string, index int, lock sync.Mutex) {
	ticker := time.NewTicker(time.Millisecond * 1000)
	defer ticker.Stop()
	for range ticker.C {
		//加锁
		lock.Lock()
		message := <-ch
		lock.Unlock()
		fmt.Println("接收到" + message)
	}
}
